<template>
	<div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="space_bottom">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务创建" prop="createTime" class="space_bottom">
              {{form.createTime}} 由 {{form.createBy}} 创建
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-form-item label="任务名称" prop="flowName">
          <el-input v-model="form.flowName" placeholder="请输入任务名称"
						size="small" class="form_long1"/>
        </el-form-item>


        <el-form-item label="安检模板" class="space_bottom">
          <el-table ref="checkIndexTable" :show-header="false"
              highlight-current-row
              @current-change="handleCheckIndexChange"
              :data="form.labSafetyCheckIndexList">
            <el-table-column label="名字" align="left" prop="name" />
          </el-table>
        </el-form-item>

        <el-form-item label-width="0">
          <el-table :data="indexItemList" default-expand-all height="400px" row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column label="编号" align="left" prop="itemNo" width="120" />
            <el-table-column label="检查指标项" align="left" prop="name" width="160" />
            <el-table-column label="检查要点" align="left" prop="spec" />
            <el-table-column label="检查状态" align="center" width="60">
              <template slot-scope="scope">
                <i v-if="scope.row.checkedStatus == 1" class="el-icon-check"></i>
              </template>
            </el-table-column>
            <el-table-column label="存在隐患" align="center" :formatter="formatterHiddenDanger" />

            <el-table-column label="附件" align="center"  width="50">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.indexId"
                  style="text-decoration: underline;"
                  size="mini"
                  type="text"
                  @click="handleManage(scope.row)"
                >查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="任务附件">
          <UploadCom ref="upload"
          @submitData="submitData"
          description="点击选择需要上传的文件"
          :userFileList="fileList"
          class="form_long" />
        </el-form-item>
      </el-form>

    <el-dialog title="整改报告" center :visible.sync="reportOpen" width="550px" @close="close" append-to-body>
      <el-form disabled ref="form" label-width="80px">
        <el-form-item label="报告附件">
          <UploadCom ref="upload"
          :userFileList="fileList"
          class="form_file" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">关 闭</el-button>
      </div>
    </el-dialog>

      <ChooseOrgan ref="chooseOrgan" @chooseUsers ="setCheckTargetOrgs" ></ChooseOrgan>
	</div>
</template>
<script>
import { listLabsafetyCheckIndex } from "@/api/labsafety/labsafetyCheckIndex";
import { addTask, updateTask } from "@/api/labsafety/task";
import ChooseUser from "../../safetyCompents/check_user.vue"
import ChooseOrgan from "../../safetyCompents/choose_organ.vue"
import UploadCom from "@/views/labdata/commons/upload.vue"
import { updateItemStatus, listTaskItem, getTaskItemFile } from "@/api/labsafety/taskItem";
export default {
  name: "CreateDialog",
  components: {ChooseUser, ChooseOrgan, UploadCom},
	props: {
		form: Object
	},
  data() {
    return {
			checkTargetOrgs: [],
      checkUsers: [],
			reviewUsers: [],
      copyToUsers: [],
      // 安全检查单表格数据
      labsafetyFormList: [],
      // 安检类型字典
      safetyCheckOptOptions: [],
      // 任务周期字典
      taskCycleOptOptions: [],
      // 整改报告字典
      rectificationTypeOptOptions: [],
      // 安检模板字典
      safetyTemplateOptOptions: [],
      // 周期版次字典
      checkFrequencyOptOptions: [],
      addItem: {
        review: false, //任务复核
        copy: false //任务抄送
      },
      fileList: [],
      indexItemList: [],
      reportOpen: false,
      // 表单校验
      rules: {
        flowName: { required: true, message: "任务名称不能为空", trigger: "blur" },
        safetyCheckOpt: { required: true, message: "安检类型不能为空", trigger: "blur" },
        safetyTemplateOptArray: { required: true, message: "安检模板不能为空", trigger: "blur" },
        taskCycleOpt: { required: true, message: "任务周期不能为空", trigger: "blur" },
        checkFrequencyOpt: { required: true, message: "周期频次不能为空", trigger: "blur" },
        startDate: { required: true, message: "任务开始不能为空", trigger: "blur" },
        rectificationTypeOpt: { required: true, message: "整改报告不能为空", trigger: "blur" },
        rectificationPeriod: { required: true, message: "整改期限不能为空", trigger: "blur" },
        checkTargetOrgs: { required: true, message: "检查对象不能为空", trigger: "change" },
        checkUsers: { required: true, message: "检查人员不能为空", trigger: "change" }
      }
    };
  },
  created() {
    this.getDicts("safetyCheckOpt").then(response => {
      this.safetyCheckOptOptions = response.data;
    });
    this.getDicts("taskCycleOpt").then(response => {
      this.taskCycleOptOptions = response.data;
    });
    this.getDicts("rectificationTypeOpt").then(response => {
      this.rectificationTypeOptOptions = response.data;
    });
    // this.getDicts("safetyTemplateOpt").then(response => {
    //   this.safetyTemplateOptOptions = response.data;
    // });
    this.getDicts("checkFrequencyOpt").then(response => {
      this.checkFrequencyOptOptions = response.data;
    });

		listLabsafetyCheckIndex().then(response => {
			this.safetyTemplateOptOptions = response.rows
		});
  },
  computed: {
      selectCheckTargetOrgs() {
        return this.checkTargetOrgs.map(item => item.orgName)
      },
      selectCheckUsers() {
        return this.checkUsers.map(item => item.nickName)
      },
      selectReviewUsers() {
        return this.reviewUsers.map(item => item.nickName)
      },
      selectCopyToUsers() {
        return this.copyToUsers.map(item => item.nickName)
      }
  },
  methods: {
    handleManage(row) {
      getTaskItemFile(row.id).then(response => {
        if(response.data && response.data.length>0){
          this.fileList = response.data
        }
        this.reportOpen = true
      })
    },
    close() {
      this.fileList = []
      this.reportOpen = false
    },
    formatterHiddenDanger(row) {
      if(row.hiddenDanger == 1) {
        return '有'
      }
      return '无'
    },
    formatterCheckedStatus(row) {
      if(row.checkedStatus == 1) {
        return '已检查'
      }
      return '未检查'
    },
    selectCheckIndexTable(formData) {
      const firstRow = formData.labSafetyCheckIndexList[0]
      this.$refs.checkIndexTable.setCurrentRow(firstRow)
      listTaskItem({indexId: firstRow.id, instanceId: formData.instanceId}).then(response => {
        this.indexItemList = this.handleTree(response.rows, "indexItemId");
      })
    },
    handleCheckIndexChange(row) {
      if (row && this.form.instanceId) {
        listTaskItem({indexId: row.id, instanceId: this.form.instanceId}).then(response => {
          this.indexItemList = this.handleTree(response.rows, "indexItemId");
        })
      }
    },
    statusFormatter(row, column) {
      if (row.indexId) {
        if (row.status == 1) {
          return '已移除'
        }
        return '正常'
      }
    },
    handleDelete(row) {
      const data = {
        id: row.id,
        status: 1
      }
      updateItemStatus(data).then(response => {
        row.status = 1
      })
    },
    handleRevert(row) {
      const data = {
        id: row.id,
        status: 0
      }
      updateItemStatus(data).then(response => {
        row.status = 0
      })
    },
    selectTargetOrgs() {
      this.$refs["chooseOrgan"].handleAdd();
    },
    // 安检类型字典翻译
    safetyCheckOptFormat(row) {
      return this.selectDictLabel(this.safetyCheckOptOptions, row.safetyCheckOpt);
    },
    // 任务周期字典翻译
    taskCycleOptFormat(row) {
      return this.selectDictLabel(this.taskCycleOptOptions, row.taskCycleOpt);
    },
    // 整改报告字典翻译
    rectificationTypeOptFormat(row) {
      return this.selectDictLabel(this.rectificationTypeOptOptions, row.rectificationTypeOpt);
    },
    // 安检模板字典翻译
    safetyTemplateOptFormat(row) {
      return this.selectDictLabel(this.safetyTemplateOptOptions, row.safetyTemplateOpt);
    },
    // 周期版次字典翻译
    checkFrequencyOptFormat(row) {
      return this.selectDictLabel(this.checkFrequencyOptOptions, row.checkFrequencyOpt);
    },
    // 表单重置
    reset() {
      // this.form = {
      //   instanceId: null,
      //   createTime: null,
      //   createBy: null,
      //   taskName: null,
      //   safetyCheckOpt: null,
      //   safetyTemplateOpt: null,
      //   taskCycleOpt: null,
      //   checkFrequencyOpt: null,
      //   startDate: null,
      //   endDate: null,
      //   rectificationTypeOpt: null,
      //   rectificationPeriod: null,
      //   taskDescription: null
      // };
      this.addItem = {
        review: false,
        copy: false
      }
			this.checkTargetOrgs = []
      this.checkUsers = []
			this.reviewUsers = []
      this.copyToUsers = []
			this.fileList = []
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.safetyCheckId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
    },
    /** 修改按钮操作 */
    handleUpdate() {
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
					this.$refs["upload"].doSubmit();
        }
      });
    },
    setCheckUsers(list) {	// 检查人员
			this.checkUsers = list
      this.form.checkUsers = '';
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.checkUsers += ','
        }
        this.form.checkUsers += item.userId
      });
    },
    setReviewUsers(list) {	// 复核人员
			this.reviewUsers = list
      this.form.reviewUsers = ''
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.reviewUsers += ','
        }
        this.form.reviewUsers += item.userId
      });
    },
    setCopyToUsers(list) {	// 抄送人员
      this.copyToUsers = list
      this.form.copyToUsers = ''
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.copyToUsers += ','
        }
        this.form.copyToUsers += item.userId
      });
    },
    setCheckTargetOrgs(list) { // 检查对象
			this.checkTargetOrgs = list
      this.form.checkTargetOrgs = ''
      list.forEach((item, index) => {
        if (index > 0) {
          this.form.checkTargetOrgs += ','
        }
        this.form.checkTargetOrgs += item.orgId
      });
    },
		clearSelect(type) {
			switch (type) {
				case 'checkUsers':
					this.setCheckUsers([])
					break;
				case 'reviewUsers':
					this.setReviewUsers([])
					break;
				case 'copyToUsers':
					this.setCopyToUsers([])
					break;
				case 'checkTargetOrgs':
					this.setCheckTargetOrgs([])
					break;
				default:
					break;
			}
		},
    removeSelect(value) {
    },
		changeTaskCycleOpt(taskCycleOptVal) {
			if (taskCycleOptVal == "1") {
				this.$set(this.form, "checkFrequencyOpt", "1")
			} else {
				this.$set(this.form, "checkFrequencyOpt", "")
			}
		},
		changeCheckFrequencyOpt(checkFrequencyOptVal) {
			if (this.form.taskCycleOpt == "2" && checkFrequencyOptVal == "1") {
        this.msgError("重复任务周期，周期频次不能为无");
				this.$set(this.form, "checkFrequencyOpt", "")
			}
		},
		/** 提交按钮 */
		submitData(allFiles) {
			this.form.files = allFiles

			if (this.form.instanceId != null) {
				updateTask(this.form).then(response => {
					this.msgSuccess("修改成功");
					this.$emit("updateForm", response.data)
				});
			} else {
				addTask(this.form).then(response => {
					this.msgSuccess("新增成功");
					this.$emit("updateForm", response.data)
				});
			}
		}
  }
};
</script>
<style type="text/css" scoped lang="scss">
  .form_long{
    width:458px;
  }
  .form_long1{
    width:556px;
  }
  .form_short{
    width:220px;
  }
  /deep/ .el-button.active{
    text-decoration: underline;
    color: #0000ee;
  }
  /deep/ .el-button.dis_active {
    color: #999999
  }
  .select_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .button_view {
      display: flex;
      align-content: center;
      justify-content: center;
  }
  .space_bottom{
    margin-bottom: 0px;
  }
</style>
